<template>
    <div class="publish-container">
        <div class="publish-header">
            <n-space align="center">
                <jb-icon icon="ri:error-warning-fill" height="20" color="#000000a3"></jb-icon>
                <span>发布状态:</span>
                <n-tag :type="appData.enable ? 'success' : 'default'">
                    {{ appData.enable ? '已发布' : '未发布' }}
                </n-tag>
                <n-button :type="appData.enable ? 'error' : 'success'" ghost size="small" @click="handleToggleEnable">
                    {{ appData.enable ? '取消发布' : '发布' }}
                </n-button>
            </n-space>
        </div>

        <div class="publish-content">
            <n-form
                    ref="formRef"
                    :model="formData"
                    label-placement="left"
                    label-width="100"
                    require-mark-placement="right-hanging"
            >
                <n-form-item label="访问地址" path="url">
                    <n-input-group>
                        <n-input v-model:value="formData.url" disabled placeholder="未发布无访问地址" readonly/>
                        <n-button type="primary" ghost @click="copyUrl">
                            <jb-icon icon="ri:file-copy-2-line"></jb-icon>&nbsp;
                            复制
                        </n-button>
                        <n-button type="primary" ghost @click="openNewPage()" >
                            <jb-icon icon="oi:globe"></jb-icon> &nbsp;
                            打开新网址
                        </n-button>
                    </n-input-group>
                </n-form-item>

                <n-form-item label="二维码" path="qrcode" >
                   <div class="flex flex-col items-center">
                       <div class="qrcode-wrapper">
                           <n-empty v-if="!formData.url" description="未发布暂无二维码"/>
                           <div v-else class="qrcode-content">
                               <n-qr-code id="qr-code" :value="formData.url"/>
                           </div>
                       </div>
                       <div class="mt-10">
                           <n-button strong secondary type="success" @click="handleDownloadQRCode()">
                               <jb-icon icon="ri:download-2-line" height="18" ></jb-icon> &nbsp;&nbsp;
                               下载二维码
                           </n-button>
                       </div>
                   </div>
                </n-form-item>
            </n-form>
        </div>
    </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {useMessage} from 'naive-ui'
import {JBoltApi} from "@/service/request/index.js";


const props = defineProps({
    appId: {
        type: String,
        required: true
    }
})

const message = useMessage()

const formData = ref({
    publishTime: '',
    url: ``
})

// 复制URL
function copyUrl() {
    if (!formData.value.url) return
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(formData.value.url)
            .then(() => {
                message.success('复制成功');
            })
            .catch((err) => {
                console.error('复制失败:', err);
            });
    } else {
        console.error('当前浏览器不支持 Clipboard API');
        // 降级方案：使用旧的 execCommand 方法
        fallbackCopyText(formData.value.url);
    }
}

function fallbackCopyText(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        document.execCommand('copy');
        message.success('复制成功');
    } catch (err) {
        console.error('复制失败（降级方案）:', err);
    }
    document.body.removeChild(textArea);
}

// 执行发布
async function handleToggleEnable() {
    await JBoltApi.get(`/aiApp/toggleEnable/${props.appId}`)
    formData.value.publishTime = new Date().toLocaleString()
    message.success("发布状态已更新")
    loadData()
}

//加载app
const appData = ref({
    enable: false,
})

function loadData() {
    JBoltApi.get(`/aiApp/getById/${props.appId}`).then(res => {
        appData.value = res.result.data
        formData.value.url = `${window.location.origin}/aiApp/${appData.value.sn}`
    })
}
//下载二维码
// 下载图片
const handleDownloadQRCode = () => {
    const canvas = document.querySelector('#qr-code canvas');
    if (canvas) {
        const url = canvas.toDataURL('image/png');
        const a = document.createElement('a');
        a.download = appData.value.name+Date.now()+'.png';
        a.href = url;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        message.success("二维码下载成功");
    } else {
        message.error("二维码下载失败");
    }
}
//打开新的网址
const openNewPage = () => {
    if (formData.value.url) {
        window.open(formData.value.url);
    } else {
        message.error("未发布无访问地址");
    }
}
onMounted(() => {
    if (props.appId) {
        loadData()
    }
})
</script>

<style scoped>
.publish-container {
    padding: 20px;
}

.publish-header {
    margin-bottom: 24px;
    padding: 16px;
    background-color: var(--n-card-color);
    border-radius: 8px;
}

.publish-content {
    background-color: var(--n-card-color);
    padding: 24px;
    border-radius: 8px;
}

.qrcode-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
}

.qrcode-content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    width: 200px;
    height: 200px;
}
.qrcode-content :deep(canvas){
    width: 200px !important;
    height: 200px !important;
}
</style>